// Hangman.cpp : implementation file
//

#include "stdafx.h"
#include "SwordBible.h"
#include "SwordBibleDoc.h"
#include "Hangman.h"
#include "BiblePage.h"
#include "ColorMgr.h"

// CHangman dialog

IMPLEMENT_DYNAMIC(CHangman, CDialog)

CHangman::CHangman(CWnd* pParent /*=NULL*/)
	: CDialog(CHangman::IDD, pParent)
  , m_entireBible(0)
{

}

CHangman::~CHangman()
{
}

void CHangman::DoDataExchange(CDataExchange* pDX)
{
  CDialog::DoDataExchange(pDX);
  DDX_Control(pDX, IDC_RICHEDIT_HANGMAN, m_richCtrl);
  DDX_Control(pDX, IDC_EDIT_GUESS, m_editGuess);
  DDX_Radio(pDX, IDC_RADIO_ENTIREBIBLE, m_entireBible);

  DDX_Control(pDX, IDC_STATIC_PIC, m_staticPic);
}


BEGIN_MESSAGE_MAP(CHangman, CDialog)
	ON_COMMAND_RANGE(ID_ALPHABET_A, ID_ALPHABET_Z, OnClickAlphabet)
	ON_BN_CLICKED(IDC_BUTTON_TRY_AGAIN, &CHangman::OnTryAgain)
	ON_WM_PAINT()
  ON_BN_CLICKED(IDC_RADIO_ENTIREBIBLE, &CHangman::OnRadioEntireBible)

  ON_BN_CLICKED(IDC_RADIO_OT, &CHangman::OnRadioOT)
  ON_BN_CLICKED(IDC_RADIO_NT, &CHangman::OnRadioNT)
  ON_BN_CLICKED(IDC_RADIO_PLACES, &CHangman::OnRadioPlaces)
  ON_BN_CLICKED(IDC_RADIO_PEOPLE, &CHangman::OnRadioPeople)
  ON_WM_CLOSE()
END_MESSAGE_MAP()


// CHangman message handlers

BOOL CHangman::OnInitDialog()
{
  CDialog::OnInitDialog();

  srand(time(NULL));

  LoadToolBar();

  ans_len = 0;

  m_richCtrl.GetRect(richRect);
  m_richCtrl.ClientToScreen(richRect);
  ScreenToClient(richRect);

  m_staticPic.GetWindowRect(paintRect);  
  paintRect.bottom -= 3;
  paintRect.top += 3;
  paintRect.left += 3;
  paintRect.right -= 3;
  ScreenToClient(paintRect);


  CFont font;
  font.CreatePointFont(120, CBiblePage::font.text_facename);
  m_editGuess.SetFont(&font);

  //ger from registry
  m_entireBible = AfxGetApp()->GetProfileInt(_T("Hangman"), _T("Radio"), 0);
  UpdateData(FALSE);

  COLORREF cr = RGB(112,138,144);
  CString color = AfxGetApp()->GetProfileString(_T("Hangman"), _T("PicColor"), CColorMgr::COLORREFtoRTF(cr)  );
	cr = CColorMgr::RTFtoCOLORREF(color);
  	

  OnPickVerse();



 pen.CreatePen( PS_SOLID, 3, cr ) ; 
 pbrush = CBrush::FromHandle( (HBRUSH)GetStockObject(NULL_BRUSH) ) ;


  return TRUE;  // return TRUE unless you set the focus to a control
  // EXCEPTION: OCX Property Pages should return FALSE
}


void CHangman::LoadToolBar()
{
  	if (!m_toolbar.CreateEx(this, TBSTYLE_FLAT|TBSTYLE_LIST|TBSTYLE_WRAPABLE|TBSTYLE_AUTOSIZE, WS_CHILD
       | WS_VISIBLE | CBRS_TOP | CBRS_TOOLTIPS | CBRS_SIZE_DYNAMIC) ||
       !m_toolbar.LoadToolBar(IDR_TOOLBAR_ALPHABET))
   {
      TRACE0("Failed to create toolbar\n");
      return;      // fail to create
   }

	// Position the control bars using RepositionBars. 
	RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);

  CToolBarCtrl& formatBar = m_toolbar.GetToolBarCtrl();

  CFont font;
  font.CreatePointFont(110, "Arial");
  formatBar.SetFont(&font, TRUE);

  m_toolbar.SetSizes(CSize(24,24),CSize(0,0));

   TBBUTTONINFO info; 
  info.dwMask = TBIF_TEXT| TBIF_IMAGE ;
  info.cbSize = sizeof(info); 
  info.iImage = -1;
 
  for(int i = 0; i < 26; i++)
  {
  CString temp(CSwordBibleDoc::alphabet[i]);
  info.pszText = (LPSTR) ((LPCTSTR)  temp);
  info.cchText = _tcsclen(temp);
  formatBar.SetButtonInfo( ID_ALPHABET_A + i, &info);
  }

 CRect rect;
 formatBar.GetItemRect(0, rect);

	// Expand the size of the Toolbar window so all controls in it would fit	
  CRect toolBarRect;
  toolBarRect.left = 10;
  toolBarRect.right = 10 + rect.Width() * 14.1;
  toolBarRect.top = 300;
  toolBarRect.bottom = 300 + rect.Height() * 3;
  formatBar.MoveWindow(toolBarRect,TRUE);
}


void CHangman::OnClickAlphabet(UINT nID)
{
	TCHAR alphabet = CSwordBibleDoc::alphabet[nID - ID_ALPHABET_A];

	m_toolbar.SendMessage((UINT) TB_ENABLEBUTTON, (WPARAM)(int) nID,  (LPARAM) MAKELONG(FALSE, 0) );

	BOOL found = FALSE;

       for(int i =0; i < ans_len; i++)
	  if( alphabet ==  verseBook.GetAt(i) )   { found = TRUE;  guessBook.SetAt(i, alphabet); }


	  if (found == TRUE)   m_editGuess.SetWindowText(guessBook);
	 else wrong_guesses++;


	 
	 if(found == TRUE && guessBook.Find(_T('#')) == -1) {

	 CString success = 	  CBiblePage::font.GetHeaderRTF();
     CString fs;
     fs.Format(_T("\\fs%d "),24);
     success += fs;

     success += _T("Success!");
     success += _T("}");

  
     m_richCtrl.SetRTF(success);

     InvalidateRect(richRect);
    
	  }



	  if(found == FALSE && wrong_guesses > 6) {

	  for(int n = 0; n < 26; n++)
	  m_toolbar.SendMessage((UINT) TB_ENABLEBUTTON, (WPARAM)(int) ID_ALPHABET_A + n,  (LPARAM) MAKELONG(FALSE, 0) );

	 CString failure  = 	  CBiblePage::font.GetHeaderRTF();
     CString fs;
     fs.Format(_T("\\fs%d "),24);
     failure += fs;

	 CString temp;
	 temp.Format(_T("The correct answer is %s. Please try again."), verseBook);
     failure += temp;
     failure += _T("}");

  
     m_richCtrl.SetRTF(failure);

     InvalidateRect(richRect);

     
	  }
	  

     InvalidateRect(paintRect);
	

}



void CHangman::OnPickVerse()
{

  UpdateData();
 
	int active = CBiblePage::active;

  wrong_guesses = 0;

  CString text = _T("");

  for(int n = 0; n < 26; n++)
	m_toolbar.SendMessage((UINT) TB_ENABLEBUTTON, (WPARAM)(int) ID_ALPHABET_A + n,  (LPARAM) MAKELONG(TRUE, 0) );


  if(m_entireBible < 3) {

  int min = 0, max = 65;

  if(m_entireBible == 1) max = 38;
  else if(m_entireBible == 2) min = 39;

  int book = min + rand() * (max - min)/RAND_MAX;
  int chap = rand() * _tstoi(CSwordBibleDoc::bookCode[book][2])/RAND_MAX; 
  int verse = (rand() * CSwordBibleDoc::VerseCount[book][chap])/RAND_MAX;

  CString key;
  verseBook = CSwordBibleDoc::bookCode[book][0];
  key.Format(_T("%s %d:%d"), verseBook ,chap, verse);

  CSwordBibleDoc::pRTFBibleModule[active]->setKey( (sword::SWKey) (CStringA) key);
  text = CSwordBibleDoc::pRTFBibleModule[active]->StripText();
}

  else if(m_entireBible == 3) {

  int idx = rand() * MAX_BIBLE_PLACES/RAND_MAX;
   verseBook = CSwordBibleDoc::BiblePlaces[idx];
  }

  else if(m_entireBible == 4) {

  int idx = rand() * MAX_BIBLE_PEOPLE/RAND_MAX;
   verseBook = CSwordBibleDoc::BiblePeople[idx];
  }


  verseBook.MakeUpper();
  guessBook = verseBook;
  ans_len = verseBook.GetLength();

  for(int i = 0; i < ans_len; i++)
    if(verseBook.GetAt(i) != _T(' ') && verseBook.GetAt(i) != _T('-')) 
      guessBook.SetAt(i, _T('#'));

  m_editGuess.SetWindowText(guessBook);


  verseText = CBiblePage::font.GetHeaderRTF();
  CString fs;
  fs.Format(_T("\\fs%d "),24);
  verseText += fs;
  verseText += text;
  verseText += _T("}");  
  m_richCtrl.SetRTF(verseText);
  RemoveTags(_T("["), _T("]"));

  InvalidateRect(richRect);
  InvalidateRect(paintRect);


}




void CHangman::OnTryAgain()
{
  OnPickVerse();
}

void CHangman::RemoveTags(CString tagStart, CString tagEnd)
{

	FINDTEXTEX ft1, ft2;
	ft1.chrg.cpMin = 0;
	ft1.chrg.cpMax = -1;
	ft1.lpstrText = tagStart;

	ft2.chrg.cpMin = 0;
	ft2.chrg.cpMax = -1;
	ft2.lpstrText = tagEnd;

	int start = 0, end = 0;


	while (true) {
	
	start = m_richCtrl.FindText(FR_DOWN , &ft1); //find the start tags  
	end = m_richCtrl.FindText(FR_DOWN , &ft2); //find the end tags  

	if(start == -1 || end == -1 || start > end) return;

	CString ref = _T("");
    m_richCtrl.SetSel(start, end+1);
    m_richCtrl.ReplaceSel(_T(""));

	ft1.chrg.cpMin = start + 1;
	ft2.chrg.cpMin = end + 1;


}
}


void CHangman::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	// TODO: Add your message handler code here
	// Do not call CDialog::OnPaint() for painting messages

  poldpen = dc.SelectObject( &pen ) ; 
  poldbrush = dc.SelectObject( pbrush ) ; 

	
	if(wrong_guesses == 0) return;

	if(wrong_guesses > 0)
    dc.Ellipse( 340,35,360,55) ;

	if(wrong_guesses > 1)
	{
      dc.MoveTo(350,55);
      dc.LineTo(350, 80);
	}

	if(wrong_guesses > 2)
	{
     dc.LineTo(330, 80);
	}

	if(wrong_guesses > 3)
	{
      dc.MoveTo(350,80);
      dc.LineTo(370, 80);
	}

  
	if(wrong_guesses > 4)
	{
      dc.MoveTo(350,80);
      dc.LineTo(350, 105);
	}

  if(wrong_guesses > 5)
	{
      dc.MoveTo(350,105);
      dc.LineTo(330, 105);
	}

    if(wrong_guesses > 6)
	{
      dc.MoveTo(350, 105);
      dc.LineTo(370, 105);
	}


  dc.SelectObject( poldbrush ) ; 
  dc.SelectObject( poldpen ) ; 

}

void CHangman::OnRadioEntireBible()
{
   OnPickVerse();
 
}

void CHangman::OnRadioOT()
{
   OnPickVerse(); 
}

void CHangman::OnRadioNT()
{
   OnPickVerse();  
}

void CHangman::OnRadioPlaces()
{
   OnPickVerse(); 
}

void CHangman::OnRadioPeople()
{
   OnPickVerse();  
}



void CHangman::OnClose()
{

  UpdateData();

 // save to registry
 AfxGetApp()->WriteProfileInt(_T("Hangman"), _T("Radio"), m_entireBible);

  CDialog::OnClose();
}

BOOL CHangman::PreTranslateMessage(MSG* pMsg)
{
  
 if(pMsg->hwnd == GetSafeHwnd() )
		if(pMsg->message == WM_LBUTTONDOWN)
    {
      CPoint pt = pMsg->pt;
      ScreenToClient(&pt); 

      if(paintRect.PtInRect(pt) == TRUE)
		  {
			CColorDialog dlg;
			if( dlg.DoModal() == IDOK )
			{	

        pen.CreatePen( PS_SOLID, 3, dlg.GetColor() ) ;
			  
				InvalidateRect(paintRect);


				// save to registry
				AfxGetApp()->WriteProfileString(_T("Hangman"), _T("PicColor"), CColorMgr::COLORREFtoRTF(dlg.GetColor()) );
			}
      }

		}

  return CDialog::PreTranslateMessage(pMsg);
}
